/*
Copyright 2007 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.CS2510.View;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JFrame;

import edu.pitt.CS2510.Coordinate;

public class View extends JFrame {
	/**
	 *
	 */
	private static final long serialVersionUID = -6866858136260615658L;
	private final int height;
	private final int width;
	private Graphics g = null;
	private ArrayList painter = null;
	private CentralBlock cb = null;

	public View(int height, int width) {
		painter = new ArrayList();
		setVisible(true);
		this.setSize(width * 20 + 300, height * 20);
		this.height = height;
		this.width = width;
		setResizable(false);
		getContentPane().setLayout(new GridLayout(height, width));
		setBackground(Color.black);
		cb = new CentralBlock(height, width);
		g = getGraphics();
		addWindowListener(new java.awt.event.WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent winEvt) {
				// Perhaps ask user if they want to save any unsaved files
				// first.
				System.exit(0);
			}
		});
	}

	public void update() {
		paint(getGraphics());
	}

	@Override
	public void paint(Graphics g) {
		g.setColor(Color.black);
		g.clearRect(0, 0, height * 20 + 300, width * 20);
		for (int i = 0; i < width; i++) {
			g.setColor(Color.gray);
			g.drawLine(i * 20, 0, i * 20, height * 20);
		}
		for (int i = 0; i < height; i++) {
			g.setColor(Color.gray);
			g.drawLine(0, i * 20, width * 20, i * 20);
		}
		for (final Iterator iter = painter.iterator(); iter.hasNext();) {
			final Shape shape = (Shape) iter.next();
			shape.draw(g);
		}
		painter.clear();
		painter.add(new CentralBlock(height, width));
	}

	public void addShape(Shape shape) {
		painter.add(shape);
	}

	public Coordinate getCentralBlockLocation() {
		return new Coordinate(cb.getX(), cb.getY());
	}
}
